import QS from '../miniprogram_npm/qs/index'
var app = getApp()
const baseUrl = app.globalData.apihost



export function request(method, url, data, file) {

    const token = wx.getStorageSync('token') || null
    const userId = wx.getStorageSync('userId')
    const ver = wx.getStorageSync('version') || null
    data.userId = userId ? userId : 0
    wx.showLoading()
    return new Promise((resolve, reject) => {
        let header = {
              'content-type': 'application/x-www-form-urlencoded',
              'g-token':token,
              'g-ver': ver
        }
        wx.request({
            url: baseUrl + url,
            method: method,
            header: header,
            data: method === 'POST' ? QS.stringify(data) : data,
            responseType: file ? "arraybuffer" : 'text',
            success: (res) => {
                console.log(res.data, res.data.status, '后台结果')
               wx.hideLoading()
                if (res && res.data.status == 0) {
                    if (res.data.content) {
                        resolve(res.data.content);
                    } else {
                        wx.showToast({
                            title: res.data.msg,
                            icon: 'none'
                        })
                    }
                    resolve(res.data.content);
                }else if(res.data.status==6001){
                    wx.showToast({
                        title: res.data.msg,
                        icon: 'none'
                    })
                    resolve(res.data.msg);
                    wx.redirectTo({
                      url: '/pages/login/login',
                    })
                    wx.removeStorageSync('userId')
                    wx.removeStorageSync('token')
                    wx.removeStorageSync('cjh')
                    wx.removeStorageSync('lastLogin')
                    wx.removeStorageSync('canAddCjh')
                    wx.removeStorageSync('isAdmin')
                } else {
                    wx.hideLoading()
                    wx.showToast({
                        title: res.data.msg,
                        icon: 'none'
                    })
                    resolve(res.data.msg);
                }
            },
            fail: (err) => {
                wx.hideLoading()
                console.log(err, '请求错误')
                wx.showToast({
                    title: err.errMsg,
                    icon: 'error'
                })
                reject(err);
            }
        })
    }).catch(err => {
        console.log(err, '--------------')
        wx.showToast({
            title: err.errMsg,
            icon: 'error'
        })
    })
}